<template>
  <!--  委外-->
  <div class="content">
    <div class="pageSearchView">
      <el-form :inline="true" :model="searchParam" class="demo-form-inline">
        <el-form-item label="物料" style="width: 250px" prop="materalId">
          <el-select v-model="searchParam.materialId" placeholder="请选择物料" filterable remote
                     :remote-method="getMaterialList">
            <el-option v-for="(item, index) of materialList" :key="index" :label="item.materialName" :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="物料状态" style="width: 250px" prop="materalId">
          <el-select v-model="searchParam.materialStatusList" placeholder="请选择" clearable collapse-tags
                     collapse-tags-tooltip filterable multiple style="width: 205px">
            <el-option v-for="item in statusList" :key="item.value" :label="item.label" :value="item.value"/>
          </el-select>
        </el-form-item>
        <el-form-item label="仓库名称">
          <el-tree-select v-model="searchParam.warehouseId" :data="wareList" check-strictly clearable filterable
                          :render-after-expand="false" :props="{
              children: 'sonList',
              label: 'warehouseName',
              value: 'id',
            }" style="width: 205px" @change="wareChange"/>
        </el-form-item>
        <el-form-item label="库位名称">
          <el-select v-model="searchParam.storageId" placeholder="请选择" clearable filterable style="width: 205px">
            <el-option v-for="item in storageList" :key="item.id" :label="item.storageName" :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="加工属性">
          <el-select v-model="searchParam.processingStatus" placeholder="请选择加工属性" clearable filterable
                     style="width: 160px">
            <el-option :key="0" label="未加工" :value="0"/>
            <el-option :key="1" label="已加工" :value="1"/>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="getList()">查询</el-button>
          <el-button :icon="Refresh" @click="resetSearch()">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="pageTableView">
      <div class="pageTableMenuView">
        <div class="pageTableTitle">列表信息</div>
        <div class="pageTableButView">
          <el-button icon="Download" type="primary" :loading="downLoading" @click="handleExport"
                     style="margin-left: 10px;">导出
          </el-button>
        </div>
      </div>
      <!-- 表格 -->
      <el-table class="pageTableClass" :data="paginatedData" border show-summary :summary-method="getSummaries"
                height="calc(100vh - 320px)">
        <el-table-column label="序号" align="center" width="70">
          <template #default="scope">
            <!-- 下标 + 1，计算公式：当前页数 * 每页大小 + 当前行的索引 + 1 --> {{
              (pageSearch.current - 1) * pageSearch.pageSize +
              scope.$index + 1
            }}
          </template>
        </el-table-column>
        <el-table-column prop="materialNo" label="物料编码" align="center" min-width="200"/>
        <el-table-column prop="materialName" label="物料名称" align="center" min-width="200"/>
        <el-table-column prop="storageName" label="库位名称" align="center" min-width="200"/>
        <el-table-column prop="count" label="数量" align="center" min-width="200"/>
        <el-table-column prop="basicUnit" label="单位" align="center" min-width="200"/>
        <el-table-column label="物料状态" prop="materialStatus" align="center" min-width="120" :formatter="formatStatus"/>
        <el-table-column label="加工属性" prop="processingStatus" align="center" min-width="120"
                         :formatter="formatProcessingAttributes"/>
      </el-table>
      <div class="pagePagination">
        <el-pagination background v-model:current-page="pageSearch.current" v-model:page-size="pageSearch.pageSize"
                       :page-sizes="[10, 20, 50, 100, 200, 500]" layout="total, sizes, prev, pager, next"
                       :total="pageTotal"
                       @size-change="handleSizeChange" @current-change="handleCurrentChange"/>
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
import {computed, reactive, ref} from 'vue';
import type {FormInstance, FormRules} from 'element-plus';
import {ElMessage, ElMessageBox} from 'element-plus';
import axiosInstance from '@/utils/http/api';
import {Delete, Edit, Plus, Refresh, Search} from '@element-plus/icons-vue';
import axios from "axios";
import moment from "moment";

onMounted(() => {
  getList();
  getOption();
});


const pageSearch = ref({
  current: 1,
  pageSize: 10
});

const formatStatus = (row, column, cellValue) => {
  switch (cellValue) {
    case 0:
      return '不可用';
    case 1:
      return '可用';
    case 2:
      return '运输中';
    case 3:
      return '生产锁定';
    case 4:
      return '不合格';
    case 5:
      return '报废';
  }
};

const formatProcessingAttributes = (row, column, cellValue) => {
  switch (cellValue) {
    case 0:
      return '未加工';
    case 1:
      return '已加工';

  }
};

const workOrderList = ref({});

const materialList = ref([]); // 物料表

const pageTotal = ref(null);//页面总数
const searchParam = ref({});//页面检索条件


// 判断质检类型
const getQualityTypeByValue = (e) => {
  let name = null;
  for (const item of qualityTypeList) {
    if (e == item.value) {
      name = item.label;
    }
  }
  return name;
};

// 质检类型
const qualityTypeList = reactive([
  {
    label: '部分送货',
    value: '1'
  },
  {
    label: '全部送货',
    value: '2'
  },
  {
    label: '未送货',
    value: '0'
  }
  // 继续添加更多检查类型...
]);


const paginatedData = ref([]);
const materiaList = ref([]);//物料表
const wareList = ref([]);//仓库
const storageList = ref({});
const procedureOrderList = ref([]);//工序订单
const supplierList = ref([]);
const storageAllList = ref([]);

const statusList = ref([{
  label: '不可用',
  value: 0
}, {
  label: '可用',
  value: 1
}, {
  label: '运输中',
  value: 2
}, {
  label: '生产锁定',
  value: 3
}, {
  label: '不合格',
  value: 4
}, {
  label: '报废',
  value: 5
}]);


const getMaterialList = (e) => {
  if (e) {
    axiosInstance.post('/api/basedataMaterial/getPage', {
      current: 1,
      pageSize: 20,
      materialName: e
    }).then(res => {
      materialList.value = res.data.records;
    });
  }
};

// 供应商远端搜索
const supplierSearch = async (query: string) => {
  if (query) {
    try {
      const response = await axiosInstance.post(`/api/basedataSupplier/getPage`, {
        current: 1,
        pageSize: 20,
        name: query
      });
      supplierList.value = await response.data.records; // 假设返回的数据直接是供应商列表
    } catch (error) {
      supplierList.value = []; // 出错时清空列表
    }
  }
};

const downLoading = ref(false);
const handleExport = () => {
  downLoading.value = true;
  axios.post('/api/warehouseStorageMaterial/warehouseReportExcel', {
    ...pageSearch.value
  }, {
    timeout: 30000, // 与 axiosInstance 的 timeout 相同
    responseType: 'blob',
    headers: {
      BearerToken: localStorage.getItem('token') || undefined // 与请求拦截器中的设置相同
    }
  })
      .then(response => {
        console.log(response);
        const url = window.URL.createObjectURL(new Blob([response.data]));
        const link = document.createElement('a');
        link.href = url;
        const formattedDate = moment().format('YYYYMMDD');
        link.setAttribute('download', '物料库存详情' + formattedDate + '.xlsx'); // 导出的格式一定要和接口返回的文件一致
        document.body.appendChild(link);
        link.click();
        window.URL.revokeObjectURL(url);
        document.body.removeChild(link);
      })
      .finally(() => {
        downLoading.value = false;
      });
};

const deviceList = ref([]);
const wareChange = (e, type) => {
  // storageList.value = {}
  axiosInstance.post('/api/basedataStorage/listByPojoPage', {
    warehouseId: e,
    current: 1,
    pageSize: 999999
  })
      .then((res) => {
        if (res.code !== 200) {
          ElMessage.warning(res.message);
          return false;
        }
        storageList.value = res.data.records;
      });
};

const getSummaries = (param) => {
  console.log(param, 'czq');
  const {columns, data} = param;
  const sums = [];

  // 初始化所有列的合计值为''
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = '合计';
      return;
    }
    sums[index] = '';
  });

  // 计算数量列的合计值
  const countIndex = columns.findIndex(column => column.property === 'count');
  if (countIndex !== -1) {
    const values = data.map(item => Number(item.count));
    sums[countIndex] = values.reduce((prev, curr) => {
      const value = Number(curr);
      if (!isNaN(value)) {
        return prev + curr;
      } else {
        return prev;
      }
    }, 0).toFixed(2);
  }

  return sums;
};


const getOption = () => {

  axiosInstance.post('/api/basedataMaterial/getPage', {
    current: 1,
    pageSize: 20
  })
      .then(res => {
        if (res.code !== 200) {
          ElMessage.error(res.message);
          return false;
        }
        materialList.value = res.data.records;
      });
  // axiosInstance.post('/api/basedataEquipment/getAll', {})
  //  .then((res) => {
  //   if (res.code !== 200) {
  //    ElMessage.warning(res.message);
  //    return false;
  //   }
  //   deviceList.value = res.data;
  //  });

  // axiosInstance.post('/api/outsourcingPlan/querySourcingPlanProcedureOrder', {})
  //  .then(res => {
  //   workOrderList.value = res.data;
  //  });

  // // 查询所有库位
  // axiosInstance.post('/api/basedataStorage/getAll', {})
  //  .then(res => {
  //   storageAllList.value = res.data;
  //  });


  // axiosInstance.post(`/api/basedataSupplier/getPage`, {
  //  current: 1,
  //  pageSize: 20
  // }).then(res => {
  //  if (res.code == 200) {
  //   supplierList.value = res.data.records;
  //  }
  // });


  // axiosInstance.post('/api/planProcedureOrder/getAll', {})
  //  .then(res => {
  //   if (res.code !== 200) {
  //    ElMessage.error(res.message);
  //    return false;
  //   }
  //   const list = res.data;
  //   const loop = [];
  //   for (const item of list) {
  //    loop.push(
  //     {
  //      value: item.id,
  //      label: item.materialName
  //     }
  //    );
  //   }
  //   procedureOrderList.value = list;
  //  });

  axiosInstance.get('/api/basedataWarehouse/treeList', {}).then(res => {
    if (res.code !== 200) {
      ElMessage.error(res.message);
      return false;
    }
    wareList.value = res.data;
  });
};

// 获取列表接口
const getList = () => {
  axiosInstance.post('/api/warehouseStorageMaterial/warehouseReport', {
        ...searchParam.value,
        ...pageSearch.value
      }
  )
      .then(res => {
        if (res.code !== 200) {
          ElMessage.error(res.message);
          return false;
        }
        // const list = res.data.records;
        // for (const item of list) {
        //  item.children = item.outsourcingWorkMaterialVOS;
        // }
        paginatedData.value = res.data.records;
        pageTotal.value = res.data.total;
      });
};

const handleSizeChange = (e) => {
  pageSearch.value.pageSize = e;
  getList();
};

const handleCurrentChange = (e) => {
  pageSearch.value.current = e;
  getList();
};

// 重置搜索条件
const resetSearch = () => {
  searchParam.value = {};
  pageSearch.value.current = 1;
  // current.value = 1
  getList();
};

</script>
<style scoped></style>
